package org.vm.cmbcdirect.wechat.service;

import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.vm.cmbcdirect.utils.HttpUtil;
import org.vm.cmbcdirect.wechat.utils.TokenThread;
import org.vm.cmbcdirect.wechat.model.component.AccessToken;
import org.vm.cmbcdirect.utils.BaseUtil;
import org.vm.cmbcdirect.wechat.model.component.Menu;

/**
 * Created by mv on 2016/3/22.
 *
 * 微信接口实现类
 */
public class CommonService {

    private final static Logger LOGGER = Logger.getLogger(CommonService.class);

    public final static String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=" +
            "client_credential&appid=APPID&secret=APPSECRET";

    public static AccessToken getAccessToken() {
        AccessToken accessToken = null;

        String requestUrl = ACCESS_TOKEN_URL.replace("APPID", BaseUtil.getAppID()).
                replace("APPSECRET", BaseUtil.getAppSecret());
        JSONObject jsonObject = HttpUtil.httpRequest(requestUrl, "GET", null);

        // 如果请求成功
        if (jsonObject != null) {
            try {
                accessToken = new AccessToken();
                accessToken.setToken(jsonObject.getString("access_token"));
                accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
            } catch (Exception e) {
                accessToken = null;
                // 获取token失败
                LOGGER.error("获取token失败 errcode:{" + jsonObject.getInt("errcode") + "} errmsg:{" +
                        jsonObject.getString("errmsg")+ "}");
            }
        }
        return accessToken;
    }

    // 菜单创建（POST） 限100（次/天）
    public static String MENU_CREATE_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";

    /**
     * 创建菜单
     *
     * @param menu 菜单实例
     * @param accessToken 有效的access_token
     * @return 0表示成功，其他值表示失败
     */
    public static int createMenu(Menu menu, String accessToken) {
        String delUrl = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" + TokenThread.accessToken.getToken();
        HttpUtil.httpRequest(delUrl, "GET", null);

        int result = 0;

        // 拼装创建菜单的url
        String url = MENU_CREATE_URL.replace("ACCESS_TOKEN", accessToken);
        // 将菜单对象转换成json字符串
        String jsonMenu = JSONObject.fromObject(menu).toString();
        // 调用接口创建菜单
        JSONObject jsonObject = HttpUtil.httpRequest(url, "POST", jsonMenu);

        if (null != jsonObject) {
            if (0 != jsonObject.getInt("errcode")) {
                result = jsonObject.getInt("errcode");
                LOGGER.error("创建菜单失败 errcode:{" + jsonObject.getInt("errcode") + "} errmsg:{" +
                        jsonObject.getString("errmsg") + "}");
            }
        }

        return result;
    }

}
